package while_lang.ast;

import java.util.Random;

import while_lang.semantics.State;

/** Nodo del AST que representa una referencia a un array.
 *  @author Leonardo Val
 */
public class Array extends Ref {
	public final Ref array;
	public final Exp index;
	
	public Array(Ref array, Exp index) {
		this.array = array;
		this.index = index;
	}

	@Override public String unparse() {
		return array.unparse() +"["+ index.unparse() +"]";
	}

	@Override public Object evaluate(State state) {
		Object[] objArray = (Object[])this.array.evaluate(state);
		return objArray[((Double)index.evaluate(state)).intValue()];
	}
	
	@Override public Object assign(State state, Object value) {

		Object[] objArray = (Object[])this.array.evaluate(state);		
		objArray[((Double)index.evaluate(state)).intValue()] = value;
		return value;
	}
	
	public static Array generate(Random random, int min, int max) {
		return new Array(
			Ref.generate(random, min-1, max-1), 
			Exp.generate(random, min-1, max-1)
		);
	}
	
	@Override public String toString() {
		return "Array("+ array +", "+ index +")";
	}

	@Override public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((array == null) ? 0 : array.hashCode());
		result = prime * result + ((index == null) ? 0 : index.hashCode());
		return result;
	}

	@Override public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Array other = (Array) obj;
		if (array == null) {
			if (other.array != null)
				return false;
		} else if (!array.equals(other.array))
			return false;
		if (index == null) {
			if (other.index != null)
				return false;
		} else if (!index.equals(other.index))
			return false;
		return true;
	}

}
